package com.lyc.yuki.module.system.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyc.yuki.common.exception.custom.ServiceException;
import com.lyc.yuki.common.result.HttpStatusEnum;
import com.lyc.yuki.module.system.domain.dto.LoginRequestDTO;
import com.lyc.yuki.module.system.domain.po.UserPO;
import com.lyc.yuki.module.system.mapper.UserMapper;
import com.lyc.yuki.module.system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: lyc
 * @Date: 2025/7/7 14:38
 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, UserPO> implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.key}")
    private String jwtKey;

    @Value("${jwt.exp}")
    private Integer jwtExp;

    @Override
    public String login(LoginRequestDTO loginRequestDTO) {
        if (loginRequestDTO.getUsername() == null || loginRequestDTO.getPassword() == null) {
            throw new ServiceException(HttpStatusEnum.USERNAME_AND_PASSWORD_IS_NULL);
        }

        LambdaQueryWrapper<UserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPO::getUsername, loginRequestDTO.getUsername());
        UserPO user;
        try {
            user = userMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            throw new ServiceException("用户名或密码错误");
        }

        String salt = user.getSalt();
        String md5Password = SecureUtil.md5(loginRequestDTO.getPassword());
        String finalPassword = SecureUtil.sha256(md5Password + salt);

        if (!finalPassword.equals(user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        // 1小时（单位是秒）
        long expTime = System.currentTimeMillis() / 1000 + jwtExp;
        return JWT.create()
                .setPayload(JWTPayload.SUBJECT, "user:" + user.getId())
                .setPayload("username", user.getUsername())
                .setPayload(JWTPayload.EXPIRES_AT, expTime)
                .setKey(jwtKey.getBytes())
                .sign();
    }
}
